<?php

namespace app\common\traits;

use app\common\facade\auth\Auth;
use app\common\service\auth\AuthAdminService;
use app\common\service\auth\AuthAgentService;
use app\common\service\stat\StatService;
use app\model\CouponOrder;
use Carbon\Carbon;
use think\Exception;
use think\facade\Db;
use think\helper\Arr;

trait Stat
{
    /**
     * 对账单
     */
    public function statements()
    {
        $statService = new StatService();

        $params = request()->all();

        if (!empty($params['is_export'])) {
            $params['page'] = '';
            $params['list_rows'] = '';
        }
        $field = Auth::from() == FROM_APP_ADMIN ? 'platform_profit' : 'profit';

        $data = $statService->statements($params);

        //导出逻辑
        if (!empty($params['is_export'])) {
            $data = $data->toArray();
            $fieldArr = [
                '日期' => 'date',
                '预估收入' => $field,
                '订单数量' => 'order_num',
                '支付金额' => 'pay_amount',
                '待结算金额' => 'no_settle',
                '已结算' => 'already_settle_amount',
            ];;
            return (new CouponOrder())->downloadExcel($fieldArr, $data, '财务对账单');
        }

        return success('', $data);
    }


    /**
     * 统计快
     */
    public function financeStat()
    {


        $params = request()->all();

        $statService = new StatService();

        $data = $statService->estimatedIncomeStat($params);

        $field = Auth::from() == FROM_APP_ADMIN ? 'platform_profit' : 'profit';


        //已结算
        $settleData = CouponOrder::query()
            ->withSearch(CouponOrder::$withSearch, $params)
            ->field('sum(' . $field . ') as already_settle_amount')
            ->where('agent_settle_status', CouponOrder::C_AGENT_SETTLE_STATUS_SUCCESS)
            ->find();

        return success('', array_merge($data->toArray(), $settleData->toArray()));

    }


    /**
     * 预览统计
     */
    public function previewStatistics()
    {

        $stats = [
            'today' => [
                'start_at' => Carbon::now()->startOfDay()->format('Y-m-d H:i:s'),
                'end_at' => Carbon::now()->endOfDay()->format('Y-m-d H:i:s'),
            ],
            'yesterday' => [
                'start_at' => Carbon::now()->subDay()->startOfDay()->format('Y-m-d H:i:s'),
                'end_at' => Carbon::now()->subDay()->endOfDay()->format('Y-m-d H:i:s'),
            ],
            'nowMonth' => [
                'start_at' => Carbon::now()->startOfMonth()->format('Y-m-d H:i:s'),
                'end_at' => Carbon::now()->endOfMonth()->format('Y-m-d H:i:s'),
            ],
            'lastMonth' => [
                'start_at' => Carbon::now()->subMonth()->startOfMonth()->format('Y-m-d H:i:s'),
                'end_at' => Carbon::now()->subMonth()->endOfMonth()->format('Y-m-d H:i:s'),
            ]
        ];

        $statService = new StatService();
        foreach ($stats as &$stat) {
            $stat['stat'] = $statService->estimatedIncomeStat($stat);
        }


        return success('', $stats);
    }

    /**
     * 图表信息
     */
    public function chart()
    {
        $params = request()->all();
        $statService = new StatService();
        return success('', $statService->chartData($params));
    }

    /**
     * 服务与统计
     */
    public function servAndAgentStat()
    {

        $statService = new StatService();
        $params = request()->all();
        $params['search_type'] = 'serv_type';

        $servData = $statService->statements($params);

        $servData = !empty($servData) ? $servData->toArray() : [];

        $servRes = [];

        $all_order_num = 0;
        //总的订单金额
        foreach ($servData as $value) {
            $all_order_num += $value['order_num'];
        }

        foreach ($servData as $value) {
            $servRes[] = [
                'value' => $value['order_num'],
                'scale' => bcmul(bcdiv($value['order_num'], $all_order_num, 2), 100, 2),
                'name' => @$value['serviceSub']['name'],
                'profit' => @$value['profit'],
                'platform_profit' => @$value['platform_profit'],
            ];
        }

        $auth = Auth::instance();

        if ($auth instanceof AuthAdminService) {

            $params['search_type'] = 'agent';
            $params['list_rows'] = 10;
            $params['order'] = 'platform_profit';
            $params['from'] = FROM_APP_AGENT;//用于显示后台的代理商利润
            $agentData = $statService->statements($params);
        }

        if ($auth instanceof AuthAgentService) {
            $params['search_type'] = 'channel';
            $params['list_rows'] = 10;
            $channelData = $statService->statements($params);
        }


        return success('', [
            'donutChart' => $servRes,
            'servData' => $servData,
            'agent' => !empty($agentData) ? $agentData : [],
            'channel' => !empty($channelData) ? $channelData : []
        ]);

    }


    /**
     * 统计报表- 佣金数据 统计
     */
    public function reportForm()
    {

        $statService = new StatService();

        $params = request()->all();

        $params['title'] = $params['name'] ?? '';

        if (Auth::from() == FROM_APP_ADMIN && $params['search_type'] ?? '' == 'agent') {
            $params['from'] = FROM_APP_AGENT;//用于显示后台的代理商利润
        }

        $data = $statService->statements($params);

        $stat = $statService->estimatedIncomeStat($params, true);

        return success('', [
            'list' => $data,
            'stat' => $stat
        ]);
    }

    /**
     * https://s1.ax1x.com/2022/09/08/vqMhlD.png
     */
    public function statServ()
    {

        $params = request()->all();

        $params['search_type'] = 'serv_type';

        $statService = new StatService();

        $data = $statService->statements($params);
        $stat = $statService->estimatedIncomeStat($params);

        return success('', [
            'serv' => $data,
            'stat' => $stat,

        ]);

    }

}